const path = require('path');
const musicModel = require('../models/music');
const fileDir = '/public/upload/';

function optUploadSing(ctx, isUpload) {
    let { title, singer, time } = ctx.request.body;
    let { file, filelrc } = ctx.request.files;
    let singObj = { title, singer, time };

    if (isUpload) { // 更新歌曲 可以不需要传文件，使用原来的歌曲/歌词路径
        singObj.file = file ? fileDir + path.parse(file.path).base : ctx.request.body.file;
        singObj.filelrc = filelrc ? fileDir + path.parse(filelrc.path).base : ctx.request.body.filelrc;
    } else {
        if (!file) return ctx.throw('歌曲必须上传');
        
        singObj.file = fileDir + path.parse(file.path).base;
        singObj.filelrc = 'no upload filelrc'; // 没有上传歌词的默认值
    }

    // 加入用户id
    singObj.uid = ctx.session.user.id;

    if (filelrc) { // 如果上传了歌词
        singObj.filelrc = fileDir + path.parse(filelrc.path).base;
    }

    return singObj;
}

const showIndex = async (ctx, next) => {
    // 根据用户的 session 中的id查询数据
    let uid = ctx.session.user.id;
    let musics = await musicModel.findMusicByUid(parseInt(uid));
    ctx.render('index', { musics });
}
const showAdd = async (ctx, next) => {
    ctx.render('add');
}
const showEdit = async (ctx, next) => {
    // ctx.query 用于获取get请求的参数
    let { id } = ctx.request.query;
    
    let musics = await musicModel.findMusicByID(parseInt(id));
    if (musics.length === 0) {
        ctx.throw('歌曲不存在');
        return;
    }
    let music = musics[0];
    ctx.render('edit', { music });
}

// 添加歌曲，歌词非必传
const addMusic = async (ctx, next) => {

    let singObj = optUploadSing(ctx);

    let result = await musicModel.addMusic(singObj);
    if (result.affectedRows === 1) {
        ctx.body = { code: '001', msg: '添加成功' };
        return;
    }
    ctx.body = { code: '002', msg: '添加失败' + result.message };
}

// 更新歌曲
const updateMusic = async (ctx, next) => {

    let singObj = optUploadSing(ctx, true);
    let { id } = ctx.request.body;
    singObj = Object.assign(singObj, { id });

    let result = await musicModel.updateMusic(singObj);
    if (result.affectedRows === 1) {
        ctx.body = { code: '001', msg: '更新成功' };
        return;
    }
    ctx.body = { code: '002', msg: '更新失败' + result.message };
}

// 删除音乐
const deleteMusic = async (ctx, next) => {
    let { id } = ctx.request.body;

    let result = await musicModel.deleteMusicByID(parseInt(id));
    // console.log(result);
    if (result.affectedRows === 0) {
        ctx.throw('删除失败' + result.message);
        return;
    }
    ctx.body = { code: '001', msg: '删除成功' };
}

module.exports = {
    showIndex,
    showAdd,
    showEdit,
    addMusic,
    updateMusic,
    deleteMusic,
}